package com.zhugang.week02;

/**
 * @program algorithms
 * @description: deleteDuplicates
 * @author: chanzhugang
 * @create: 2022/05/29 17:40
 */
public class DeleteDuplicates2 {

    /**
     * 83. 删除排序链表中的重复元素
     *
     * @param head
     * @return
     */
    public ListNode deleteDuplicates(ListNode head) {
        // 开辟新虚拟头节点，tail指向虚拟头节点，遍历head，不相同的节点追加到尾结点
        ListNode virtualNode = new ListNode(-101, null);
        ListNode tail = virtualNode;
        ListNode p = head;
        while (p != null) {
            ListNode temp = p.next;
            if (p.val != tail.val) {
                tail.next = p;
                tail = p;
                p.next = null;
            }
            p = temp;
        }
        return virtualNode.next;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}